package com.googlecode.xbeandatasource.common;

import static java.lang.System.out;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;


import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import com.googlecode.xbeandatasource.common.Employee;
import com.googlecode.xbeandatasource.xstream.XBStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * @author Johny Huang
 *
 */
public class XStreamXpathParser {

	public final static Object parse(Object obj,String expression) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException{
		XBStream xstr=new XBStream(new DomDriver());
		ByteArrayOutputStream output=new ByteArrayOutputStream();
		xstr.processAnnotations(Employee.class);
		xstr.toXML(obj, output);

		DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
	    domFactory.setNamespaceAware(true); // never forget this!
	    DocumentBuilder builder = domFactory.newDocumentBuilder();
	    
	    Document doc = builder.parse(new ByteArrayInputStream(output.toByteArray()));
	    out.println(output);

	    XPathFactory factory = XPathFactory.newInstance();
	    XPath xpath = factory.newXPath();
	    XPathExpression expr= xpath.compile(expression);

	    return expr.evaluate(doc, XPathConstants.STRING);
	}
}
